package cn.znzz.cjm.basic.service.impl;

import cn.znzz.cjm.basic.constant.LoginConstant;
import cn.znzz.cjm.basic.exception.BusinessException;
import cn.znzz.cjm.basic.service.IVerifyCodeServie;
import cn.znzz.cjm.basic.util.StrUtils;
import cn.znzz.cjm.user.domain.User;
import cn.znzz.cjm.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServieImpl implements IVerifyCodeServie {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void sendSmsCode(Map<String,String> param) {

        String phone = param.get("phone");
        String type = param.get("type");
        //1.手机号不为空
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(type)){
            throw new BusinessException("数据不能为空");
        }

        //检验验证码是否有效（根据key从redis中能获取的数据，并且时间不过三分钟）
        String businessKey= "";

        if("register".equals(type)){
            //注册
            //2.手机号不能被注册
            User user=userMapper.loadByPhone(phone);
            if(user!=null){
                throw new BusinessException("手机号码已经被注册");
            }
            businessKey=LoginConstant.PHONE_REGISTER + phone;
        }else if("binder".equals(type)){
            //微信
            businessKey=LoginConstant.PHONE_BINDER + phone;
        }
        sendCode(businessKey);
    }
    //抽取发送验证码方法
    public void sendCode(String businessKey){
        Object codeTmp=redisTemplate.opsForValue().get(businessKey);
        String code="";
        if(codeTmp!=null){

            //1.拿到了值，验证码没有失效
            Long oldSendTime=Long.valueOf(codeTmp.toString().split(":")[1]);
            //1.1 判断是否过了重发的时间
            if((System.currentTimeMillis() -oldSendTime.longValue()) <=1*60*1000){
                //1.1.1 没过时间：请勿重复发送
                throw new BusinessException("请不要重复获取验证码");
            }
            //1.1.2 过了时间：使用原来的验证码
            code=codeTmp.toString().split(":")[0];
        }else{
            //2. 拿不到值 验证码时效或者第一次发送
            //2.1 生成新的验证码
            code= StrUtils.getComplexRandomString(4);
        }

        //3. 保存验证码，设置key的过期时间为三分钟
        String codeValue=code+":"+System.currentTimeMillis();
        redisTemplate.opsForValue().set(businessKey,
                codeValue,
                3,
                TimeUnit.MINUTES);
        //4.调用短信发送接口，将验证码发送给客户手机号
        System.out.println("你的宠物乐园验证码是："+code+"请在三分钟内使用");
    }
}














